/**注册 */
import React from "react";
import { observer } from "mobx-react";
import { useStore } from "../stores/index";
import styled from "styled-components";
import { Button, Form, Input } from "antd";

const FormContainer = styled.div`
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 2px 2px 4px 0 rgba(0, 0, 0, 0.2);
`;
const Title = styled.h1`
  text-align: center;
`;

const Component = observer(() => {
  // eslint-disable-next-line
  const { AuthStore } = useStore();
  // 提交
  const onFinish = (values) => {
    AuthStore.setIsUsername(values.username)
    AuthStore.setIsPassword(values.password)
    AuthStore.register().then((response)=>{
      console.log("注册成功")
    }).catch(()=>{
      console.log("注册失败")
    })
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  /**表单验证 */
  const validateUsername = (rule,value)=>{
    if(/\W/.test(value)) return  Promise.reject("只能数字字母下划线");
    if(value.length < 4 || value.length > 10) return Promise.reject("长度为4~10个字符");
    return Promise.resolve()
  }
  /**验证密码是否一致 */
  const validateConfirm = ({getFieldValue})=>({
    validator(rule,value) {
      if(getFieldValue("password") === value) return Promise.resolve()
      return Promise.reject("两次密码不一致")
    }
  })
  

  return (
    <FormContainer>
      <Title>注册</Title>
      <Form
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        name="basic"
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            { required: true, message: "请输入用户名" },
            {validator:validateUsername}
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[
            { required: true, message: "请输入密码" },
            { min: 4, message: "最少4个字符" },
            { max: 10, message: "最大是个字符" },
          ]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item
          label="确认密码"
          name="confirmPassword"
          rules={[
            { required: true, message: "请输入重复密码" },
            validateConfirm
          ]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 11, span: 1 }}>
          <Button type="primary" htmlType="submit" >
            提交
          </Button>
        </Form.Item>
      </Form>
    </FormContainer>
  );
});

export default Component;
